package com.mall.common.hessian.impl;

import static com.mall.common.Constants.DEFAULT_PAGE_SIZE;

import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mall.common.bean.Pager;
import com.mall.common.hessian.BaseHessian;

public class BaseHessianImpl implements BaseHessian {
	
	protected static Log log = LogFactory.getLog("hessian"); 
	protected static final JsonConfig jsonConfig = new JsonConfig();
	
	static{
		jsonConfig.setJsonPropertyFilter(new PropertyFilter() {

			@Override
			public boolean apply(Object arg0, String arg1, Object arg2) {
				return null == arg2;
			}
			
		});
		
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
			
			@Override
			public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
				if(arg1 != null){
					return ((Date)arg1).getTime();
				}
				return null;
			}
			
			@Override
			public Object processArrayValue(Object arg0, JsonConfig arg1) {
				if(arg1 != null){
					return ((Date)arg0).getTime();
				}
				return null;
			}
		});
	}
	
	public Pager newPager(Integer page, Integer size){
		Pager pager = new Pager();
		pager.setPageNumber(page == null ? 1 : page);
		pager.setPageSize(size == null ? DEFAULT_PAGE_SIZE : size);
		return pager;
	}
	
	public String pagerToJson(Pager pager) {
		JSONArray array = new JSONArray();
		if(pager != null && pager.getList() != null){
			array = JSONArray.fromObject(pager.getList());
		}
		return array.toString();
	}
	
	public String listToJson(List<? extends Object> list) {
		JSONArray array = new JSONArray();
		if(list != null && list.size() > 0){
			array = JSONArray.fromObject(list, jsonConfig);
		}
		return array.toString();
	}
	
	public String objToJson(Object obj) {
		JSONObject json = new JSONObject();
		if(obj != null ){
			json = JSONObject.fromObject(obj, jsonConfig);
		}
		return json.toString();
	}
	
}